package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.GoodsStoreMapper;
import com.qianniu.napi.admin.mapper.StoreStatMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.FanActor;
import com.qianniu.napi.admin.service.akka.FanliActor;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class HexiaoController {

    private static final Logger logger = LoggerFactory.getLogger(HexiaoController.class);
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IChoujiangService choujiangService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IQnpay qnpay;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IChoujiangLogService choujiangLogService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IHexiaoLogService hexiaoService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IHexiaoLogService hexiaoLogService;
    @Autowired
    private StoreStatMapper storeStatMapper;
    @Autowired
    private GoodsStoreMapper goodsStoreMapper;

    @RequestMapping("/api/order/hxok")
    @ResponseBody
    public Jinfo hxok(@RequestParam("ma") String ma) {
        Jinfo info = new Jinfo();

//        logger.info("=====api/order/hxok key=" + key);
//        String txt = AesUtil.decrypt(ma, EncryptUtil.md5t16(key));
        logger.info("====================/api/order/hxok ma=" + ma);
        String key = ObjectUtil.getMid() + ObjectUtil.getAppid() + ObjectUtil.getMpid();
        logger.info("====================/api/order/hxok key=" + key);
        String txt = AesUtil.decrypt(ma, EncryptUtil.md5t16(key));
        String rkey = txt;

        // 确认核销
        if (!redisService.isExists(rkey)) {
            info.setCode(1);
            info.setMsg("该二维码已被核销或失效");
            return info;
        }

        HexiaoLog hexiao = hexiaoService.selectOne(new EntityWrapper<HexiaoLog>().eq("ma", txt));
        // 确认核销
        if (redisService.isExists(rkey + "_hxok") || (hexiao != null && hexiao.getConfirm() == 1)) {
            info.setCode(1);
            info.setMsg("该二维码已核销");
            return info;
        } else {
            redisService.set(rkey + "_hxok", "1", 1, TimeUnit.MINUTES);
            hexiao.setConfirm(1);
            hexiao.setModifytime(new Date());
            hexiao.updateById();
        }

        logger.info("=====/api/order/hxok txt=" + txt);
        String[] datastr = txt.split("__");

        String type = datastr[1];
        String guid = datastr[2];
        String ywdata = datastr[3];
        // random(16)+"__"+type+"__"+guid+"__"+ywdata+"__"+timestamp+"__"+mpid+"__"+sid
        if (datastr.length != 7) {
            info.setCode(1);
            info.setMsg("未识别的二维码信息");
            return info;
        }

        redisService.del(rkey);
        User user = redisService.getUser();
        if (type.equals("jifendh")) {//积分兑换

            String[] ywdatastr = ywdata.split("#");
            BigDecimal jfcout = new BigDecimal(ywdatastr[0]);
            Long gid = Long.valueOf(ywdatastr[1].split("@")[0]);
            logger.info("--------------------------------------gid=" + gid);
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,sid").eq("id", gid));
            logger.info("--------------------------------------user.getSid()=" + user.getSid());
            if (goods != null && goods.getSid() != null && user.getIsMch().intValue() == 1 && goods.getSid().intValue() != user.getSid().intValue()) {
                info.setCode(1);
                info.setMsg("该兑换商品不是该商家所有无法兑换");
                return info;
            }

            User guser = redisService.getUserByGuid(guid);
            Long uid = guser.getId();

            boolean flag = false;
            JifenFlow jf = new JifenFlow();
            jf.setCreatetime(new Date());
            jf.setIotype(IotypeEnum.output.getVal());
            jf.setIsConfirm(1);
            jf.setConfirmDate(new Date());
            jf.setJftype(JftypeEnum.duihuan.getVal());
            jf.setMid(ObjectUtil.getMid());
            jf.setMpid(ObjectUtil.getMpid());
            jf.setRemark("用户积分兑换商品");
            jf.setUid(uid);
            jf.setNum(jfcout);
            jf.setState(1);
            jf.setSn(StringUtil.getSnNo("JD"));
//            jf.insert();

            Jifen njifen;
            while (!flag) {

                Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
                njifen = new Jifen();

                long version = jifen.getVersion();
                njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
                njifen.setModifytime(new Date());
                njifen.setModifier(uid);
                njifen.setVersion(version + 1);

                flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
                if (flag) {
                    jf.insertOrUpdate();
                    // 返利推荐人【适用于恰恰全积分兑换平台】
                    AkkaServer.system.actorOf(Props.create(FanliActor.class))
                            .tell(Constants.AKKA_FX_HEXIAO_OK + "@" + jf.getUid() + "@" + jfcout + "@" + XffanType.jifen.getVal(), ActorRef.noSender());
                }
            }

            // 积分转换到商家
            uid = ObjectUtil.getUid();
            flag = false;

            jf.setId(null);
            jf.setIotype(IotypeEnum.input.getVal());
            jf.setJftype(JftypeEnum.hexiao.getVal());
            jf.setRemark("商家扫码核销积分兑换商品");
            jf.setUid(uid);

            while (!flag) {

                Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
                njifen = new Jifen();

                long version = jifen.getVersion();
                njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
                njifen.setModifytime(new Date());
                njifen.setModifier(uid);
                njifen.setVersion(version + 1);

                flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
                if (flag) {
                    jf.insert();
                    // 商家收款返利推荐人【适用于恰恰全积分兑换平台】
                    AkkaServer.system.actorOf(Props.create(FanliActor.class))
                            .tell(Constants.AKKA_FX_HEXIAO_OK + "@" + uid + "@" + jfcout + "@" + XffanType.jifen.getVal(), ActorRef.noSender());
                }
            }
        } else if (type.equals("yuyuedh")) {// 预约订单核销

            String[] ywdatastr = ywdata.split("#");
            BigDecimal money = new BigDecimal(ywdatastr[0]);
            Long oid = new Long(ywdatastr[1]);
            User guser = redisService.getUserByGuid(guid);
            Order order = orderService.selectById(oid);

            if (order == null) {
                info.setCode(1);
                info.setMsg("不存在该订单商品");
                return info;
            }
            if (order.getStatus() == StatusEnum.commenting.getVal()) {
                info.setCode(1);
                info.setMsg("该预约已核销");
                return info;
            }
            MerchantConfig mconfig = redisService.getMconfig();

            order.setStatus(mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1 ? StatusEnum.commenting.getVal() : StatusEnum.finish.getVal());
            order.setConfirmtime(new Date());
            order.setModifytime(new Date());
            order.setModifier(ObjectUtil.getUid());
            if(ObjectUtil.getSid()!=null){
                order.setSid(ObjectUtil.getSid());
                order.setSname(storeService.selectById(ObjectUtil.getSid()).getName());
            }
            order.setHxtime(hexiao.getModifytime());
            order.updateById();

            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setStatus(mconfig.getShowCommet() != null && mconfig.getShowCommet() == 1 ? StatusEnum.commenting.getVal() : StatusEnum.finish.getVal());
            orderGoods.setModifytime(new Date());
            orderGoods.setModifier(ObjectUtil.getUid());
            if(ObjectUtil.getSid()!=null){
                orderGoods.setSid(order.getSid());
                orderGoods.setSname(order.getSname());
            }
            orderGoodsService.update(orderGoods, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));

            //更新商品核销数
            logger.info("---------------------------------------------------update setHexiaoshu for hexiao at gid=" + order.getGid());
            Goods goods = goodsService.selectById(order.getGid());
            Goods ngoods = new Goods();
            ngoods.setId(order.getGid());
            if (goods.getType().intValue() == YXType.jizan.getVal()
                    || order.getType().intValue() == YXType.toupiao.getVal() || order.getType().intValue() == YXType.choujiang.getVal()) {
                ngoods.setHexiaoshu(goods.getHexiaoshu() == null ? 1 : goods.getHexiaoshu() + 1);
            } else {
                ngoods.setHexiaoshu(goods.getHexiaoshu() == null ? order.getGoodsNumber() : goods.getHexiaoshu() + order.getGoodsNumber());
            }

            ngoods.setModifytime(new Date());
            ngoods.updateById();

            //核销领取货之后处理自购返奖励
            //发货15天后处理自购返奖励
            //===待完善===
            if (FantimeType.hexiao.getVal() == order.getFantimeType().intValue())
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_ZIGOUFAN + "@" + order.getId() + "@" + FantimeType.hexiao.getVal(), ActorRef.noSender());

            //===商家入账处理
            if (order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_STORE_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //===盟主入账处理
            if (order.getLmfan() != null && order.getLmfan().doubleValue() > 0 &&
                    order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_MENGZHU_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //===平台入账处理
            if (order.getPtfan() != null && order.getPtfan().doubleValue() > 0 &&
                    order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_PLATFORM_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //领取货之后分销结算，触发时机：扫码核销|确认收货【点击确认收货】
            //商品分享直推奖励
            logger.info("---------------------------------------------------hxok order.getSharefan()=" + order.getSharefan());
            logger.info("---------------------------------------------------hxok order.getFantimeType()=" + order.getFantimeType());
            if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                    && order.getFantimeType().intValue() == FantimeType.hexiao.getVal()) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_SHAREFAN + "@" + order.getId(), ActorRef.noSender());
            }

            //商品分销奖励
            if (mconfig.getIsFenxiao().intValue() == 1 && order.getFantimeType().intValue() == FantimeType.hexiao.getVal()
                    && order.getFxe1() != null && order.getFxe1().doubleValue() > 0) {
//                AkkaServer.system.actorOf(Props.create(OrderActor.class))
//                    .tell(Constants.AKKA_MSG_ORDER_FENXIAOFAN + "@" + order.getId(), ActorRef.noSender());
            }

        } else if (type.equals("yhqdh")) {// 优惠券核销
            String[] ywdatastr = ywdata.split("#");

            Long yhqid = new Long(ywdatastr[1]);
            String couponId = ywdatastr.length >= 3 ? ywdatastr[2] : "";
            User guser = redisService.getUserByGuid(guid);

            Wrapper<Coupon> wrapper = new EntityWrapper<Coupon>()
                    .eq("uid", guser.getId());
            if (!Strings.isNullOrEmpty(couponId)) wrapper.eq("id", couponId);
            else wrapper.eq("tplid", yhqid);

            Coupon coupon = couponService.selectOne(wrapper);
            logger.debug("===============================yhqdh logic coupon=" + JSON.toJSONString(coupon));
            if (coupon == null) {
                info.setCode(1);
                info.setMsg("该优惠券失效");
                return info;
            }
            if (coupon.getIsUsed() == 1) {
                info.setCode(1);
                info.setMsg("该优惠券已被使用");
                return info;
            }
            if (coupon.getIsOutdate() == 1) {
                info.setCode(1);
                info.setMsg("该优惠券已过期");
                return info;
            }

            coupon.setIsUsed(1);
            coupon.setIsUnused(0);
            coupon.updateById();

            CouponTpl ctpl = couponTplService.selectById(coupon.getTplid());
            CouponTpl ncouponTpl = new CouponTpl();
            ncouponTpl.setId(ctpl.getId());
            ncouponTpl.setUsed(ctpl.getUsed() == null ? 1 : ctpl.getUsed() + 1);
            ncouponTpl.setModifytime(new Date());
            ncouponTpl.updateById();

            logger.debug("====================================ctpl=" + JSON.toJSONString(ctpl));
            //扫码核销，不支持分销券分销，不支持
            boolean jiang = true;
            //活动过期不奖励
            if (ctpl.getEndtime() != null &&
                    Long.parseLong(DateUtil.getToday().replaceAll("-", "")) >
                            Long.parseLong(ctpl.getEndtime().replaceAll("-", ""))) {
                jiang = false;
            }
            if (ctpl.getFanshu() != null && ctpl.getFxshu() > 0
                    && ctpl.getFanshu() >= ctpl.getFxshu()) {
                jiang = false;
            }
            //分销类型@0:无奖励(普通券)；
            // 1：普通分享奖励(推荐有礼)(核销时出发奖品)；
            // 2：裂变红包（分享用户时触发红包）；
            // 3：分销奖励（优惠买单时触发奖励）；
            if (ctpl.getFenxiao() != null && ctpl.getFenxiao().intValue() == Qfxtype.none.getVal()
                    || ctpl.getFenxiao().intValue() == Qfxtype.hongbao.getVal()
                    || ctpl.getFenxiao().intValue() == Qfxtype.fenxiao.getVal()) {
                jiang = false;
            }
            if (coupon.getZfuid() == null) jiang = false;

            if (jiang) {
                // 1：普通分享奖励(推荐有礼)(核销时出发奖品)；
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_QUAN_SHARE_PAY + "@" + coupon.getZfuid() + "@" + ctpl.getId() + "@"
                                + coupon.getId() + "@" + FantimeType.hexiao.getVal(), ActorRef.noSender());
            }

        } else if (type.equals("yhqtykdh")) {//优惠券体验卡核销
            String[] ywdatastr = ywdata.split("#");

            Long yhqid = new Long(ywdatastr[1]);
            String couponId = ywdatastr.length >= 3 ? ywdatastr[2] : "";
            User guser = redisService.getUserByGuid(guid);

            Wrapper<Coupon> wrapper = new EntityWrapper<Coupon>()
                    .eq("uid", guser.getId()).eq("id", couponId);
            Coupon coupon = couponService.selectOne(wrapper);

            if (coupon == null) {
                info.setCode(1);
                info.setMsg("该优惠券失效");
                return info;
            }
            if (coupon.getIsUsed() == 1) {
                info.setCode(1);
                info.setMsg("该优惠券已被使用");
                return info;
            }
            if (coupon.getIsOutdate() == 1) {
                info.setCode(1);
                info.setMsg("该优惠券已过期");
                return info;
            }
            if (coupon.getType().intValue() == 10 && coupon.getCost().intValue() <= coupon.getUsemin().intValue()) {
                info.setCode(1);
                info.setMsg("该次卡已被使用完毕");
                return info;
            }

            coupon.setUsemin(coupon.getUsemin().add(new BigDecimal(1)));
            if (coupon.getType().intValue() == 10 && coupon.getCost().intValue() == coupon.getUsemin().intValue()) {
                coupon.setIsUsed(1);
                coupon.setIsUnused(0);
            }
            coupon.updateById();

        } else if (type.equals("jiangpindh")) {// 奖品核销
            String[] ywdatastr = ywdata.split("#");

            Long cjlogid = new Long(ywdatastr[0]);
            Long cjid = new Long(ywdatastr[1]);

            User guser = redisService.getUserByGuid(guid);

            ChoujiangLog choujiangLog = choujiangLogService.selectById(cjlogid);
            if (choujiangLog == null) {
                info.setCode(1);
                info.setMsg("该奖品已失效");
                return info;
            } else if (choujiangLog.getIslingqu() == 1) {
                info.setCode(1);
                info.setMsg("该奖品已被领取");
                return info;
            } else if (choujiangLog.getIsguoqi() == 1) {
                info.setCode(1);
                info.setMsg("该奖品已被过期");
                return info;
            }

            choujiangLog.setIslingqu(1);
            choujiangLog.updateById();

        } else if (type.equals("zitihx")) {//自提核销
            // ywdata 格式：
            String[] ywdatastr = ywdata.split("#");

            Long yhqid = new Long(ywdatastr[1]);
            User guser = redisService.getUserByGuid(guid);

//            OrderGoods ogoods = orderGoodsService.selectOne(new EntityWrapper<OrderGoods>()
//                                    .eq("id",yhqid)
//                                    .eq("uid",guser.getId()));
            Order order = orderService.selectById(yhqid);
            logger.info("----------------------------hxok order=" + JSON.toJSONString(order));
            if (order == null) {
                info.setCode(1);
                info.setMsg("不存在该订单商品");
                return info;
            }
            if (order.getStatus() == StatusEnum.commenting.getVal()) {
                info.setCode(1);
                info.setMsg("该商品已领取");
                return info;
            }

            order.setStatus(StatusEnum.commenting.getVal());
            order.setConfirmtime(new Date());
            order.setModifytime(new Date());
            order.setModifier(ObjectUtil.getUid());
            if(ObjectUtil.getSid()!=null){
                order.setSid(ObjectUtil.getSid());
                order.setSname(storeService.selectById(ObjectUtil.getSid()).getName());
            }
            order.setHxtime(hexiao.getModifytime());
            order.updateById();

            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setStatus(StatusEnum.commenting.getVal());
            orderGoods.setModifytime(new Date());
            orderGoods.setModifier(ObjectUtil.getUid());
            if(ObjectUtil.getSid()!=null){
                orderGoods.setSid(order.getSid());
                orderGoods.setSname(order.getSname());
            }
            orderGoodsService.update(orderGoods, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));

            //更新商品核销数
            logger.info("---------------------------------------------------update setHexiaoshu for hexiao at gid=" + order.getGid());
            Goods goods = goodsService.selectById(order.getGid());
            Goods ngoods = new Goods();
            ngoods.setId(order.getGid());
            if (goods.getType().intValue() == YXType.jizan.getVal()
                    || order.getType().intValue() == YXType.toupiao.getVal() || order.getType().intValue() == YXType.choujiang.getVal()) {
                ngoods.setHexiaoshu(goods.getHexiaoshu() == null ? 1 : goods.getHexiaoshu() + 1);
            } else {
                ngoods.setHexiaoshu(goods.getHexiaoshu() == null ? order.getGoodsNumber() : goods.getHexiaoshu() + order.getGoodsNumber());
            }

            ngoods.setModifytime(new Date());
            ngoods.updateById();

            //核销领取货之后处理自购返奖励
            //发货15天后处理自购返奖励
            //===待完善===
            if (FantimeType.hexiao.getVal() == order.getFantimeType().intValue())
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_ZIGOUFAN + "@" + order.getId() + "@" + FantimeType.hexiao.getVal(), ActorRef.noSender());

            //===商家入账处理
            if (order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_STORE_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //===盟主入账处理
            if (order.getLmfan() != null && order.getLmfan().doubleValue() > 0 &&
                    order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_MENGZHU_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //===平台入账处理
            if (order.getPtfan() != null && order.getPtfan().doubleValue() > 0 &&
                    order.getSid() != null && order.getSid().longValue() > 0) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_PLATFORM_PAY + "@" + order.getId(), ActorRef.noSender());
            }

            //领取货之后分销结算，触发时机：扫码核销确认收货【点击确认收货】
            //商品分享直推奖励
            logger.info("---------------------------------------------------hxok order.getSharefan()=" + order.getSharefan());
            logger.info("---------------------------------------------------hxok order.getFantimeType()=" + order.getFantimeType());
            if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                    && order.getFantimeType().intValue() == FantimeType.hexiao.getVal()) {
                AkkaServer.system.actorOf(Props.create(OrderActor.class))
                        .tell(Constants.AKKA_MSG_ORDER_SHAREFAN + "@" + order.getId(), ActorRef.noSender());
            }

            //商品分销奖励
            MerchantConfig mconfig = redisService.getMconfig();
            if (mconfig.getIsFenxiao().intValue() == 1 && order.getFantimeType().intValue() == FantimeType.hexiao.getVal()
                    && order.getFxe1() != null && order.getFxe1().doubleValue() > 0) {
//                AkkaServer.system.actorOf(Props.create(OrderActor.class))
//                    .tell(Constants.AKKA_MSG_ORDER_FENXIAOFAN + "@" + order.getId(), ActorRef.noSender());
            }

            AkkaServer.system.actorOf(Props.create(FanActor.class))
                    .tell(Constants.AKKA_MSG_HEXIAO_FAN + "@" + ObjectUtil.getUid() + "@" + order.getMpid()+ "@" + order.getId(), ActorRef.noSender());
        }

        if (ObjectUtil.getSid() != null) {

            // 商家核销+1
            Store store = storeService.selectOne(new EntityWrapper<Store>()
                    .setSqlSelect("id,zhexiao,jrhexiao,xdhexiao,renqi").eq("id", ObjectUtil.getSid()));
            if (store != null) {
                store.setZhexiao(store.getZhexiao() + 1);
                store.setJrhexiao(store.getJrhexiao() + 1);
                store.setRenqi(store.getRenqi() + 10);
                store.setModifytime(new Date());
                store.setModifier(ObjectUtil.getUid());
                store.updateById();
            }

            StoreStat storeStat = storeStatMapper.selectById(store.getId());
            if (storeStat == null) {
                storeStat = new StoreStat();
                storeStat.setStoreid(store.getId());
            }
            storeStat.setStorename(store.getName());
            storeStat.setStorepic(store.getThumb());
            storeStat.setRenqi(storeStat.getRenqi() + 10);
            storeStat.setHexiaos(storeStat.getHexiaos() + 1);
            storeStat.updateById();
        }

        return info;
    }

    @RequestMapping("/api/maccount/hexiao")
    @ResponseBody
    public Jinfo sjhexiao(@RequestParam("ma") String ma) {

        logger.info("=====/api/maccount/hexiao ma=" + ma);

        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(ma)) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        User user = redisService.getUser();
        if (user == null || (user.getIsMch() != 1 && user.getIsPlatform() != 1)) {
            info.setCode(1);
            info.setMsg("对不起，您暂无权限操作");
            return info;
        }

        try {
            ma = java.net.URLDecoder.decode(ma, "UTF-8");
            logger.info("=====after decode ma=" + ma);
        } catch (Exception e) {
            logger.error("======hexiao decode ma error", e);
            info.setCode(5);
            info.setMsg("该二维码信息异常");
            return info;
        }
        int cout = hexiaoLogService.selectCount(new EntityWrapper<HexiaoLog>()
                .eq("md5", EncryptUtil.md5(ma))
                .eq("confirm", 1));
        if (cout > 0) {
            info.setCode(1);
            info.setMsg("对不起，该码已被核销过");
            return info;
        }

        String key = ObjectUtil.getMid() + ObjectUtil.getAppid() + ObjectUtil.getMpid();
        logger.info("=====/api/maccount/hexiao key=" + key);

        Long ts = new Date().getTime();
        String txt = AesUtil.decrypt(ma, EncryptUtil.md5t16(key));

        logger.info("=====/api/maccount/hexiao txt=" + txt);
        String[] datastr = txt.split("__");
        // random(16)+"__"+type+"__"+guid+"__"+ywdata+"__"+timestamp+"__"+mpid+"__"+sid
        if (datastr.length != 7) {
            info.setCode(1);
            info.setMsg("未识别的二维码信息");
            return info;
        }
        try {
            Long time = Long.valueOf(datastr[4]);
            // 默认5分钟失效
            if (ts - time > 5 * 60 * 1000) {
                info.setCode(1);
                info.setMsg("该二维码失效");
                return info;
            }
        } catch (Exception e) {
            logger.error("=====hexiao ma error", e);
            info.setCode(5);
            info.setMsg("该二维码信息异常");
            return info;
        }

        HexiaoLog hexiao = new HexiaoLog();
        hexiao.setConfirm(0);
        hexiao.setMid(ObjectUtil.getMid());
        hexiao.setMpid(ObjectUtil.getMpid());
        hexiao.setUid(ObjectUtil.getUid());
        hexiao.setMa(txt);
        hexiao.setMd5(EncryptUtil.md5(txt));
        hexiao.setCreatetime(new Date());

        String type = datastr[1];
        String guid = datastr[2];
        String ywdata = datastr[3];
        Map map = new HashMap<String, Object>();
        map.put("type", type);

        if (type.equals("yajindh")) {
            Double money = Double.valueOf(ywdata);
            User guser = redisService.getUserByGuid(guid);
            hexiao.setHxuid(guser.getId());
            hexiao.setJiazhi(new BigDecimal(Double.valueOf(ywdata)));
            hexiao.setRealpay(new BigDecimal(Double.valueOf(ywdata)));
            hexiao.insert();

            map.put("state", 1);
            map.put("guid", guid);
            map.put("ywdata", Double.valueOf(ywdata));
            String rkey = Constants.REDIS_TYAJIN + guid;
            redisService.set(rkey, redisService.getUserByGuid(guid).getOpenid() + "__" + money, 10, TimeUnit.MINUTES);
        } else if (type.equals("coupon")) {

        } else if (type.equals("jifendh")) {// 积分兑换
            String[] ywdatastr = ywdata.split("#");
            Integer jifen = Integer.valueOf(ywdatastr[0]);
            User guser = redisService.getUserByGuid(guid);
            hexiao.setJiazhi(new BigDecimal(jifen));
            hexiao.setHxuid(guser.getId());
            hexiao.insert();

            Jifen jf = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", guser.getId()));
            BigDecimal zero = new BigDecimal(0);
            if (jf == null) {
                jf = new Jifen();
                jf.setHuafei(0);
                jf.setTotal(zero);
                jf.setVersion(1l);
                jf.setState(1);
                jf.setMid(ObjectUtil.getMid());
                jf.setMpid(ObjectUtil.getMpid());
                jf.setUid(guser.getId());
                jf.setRemark("积分兑换触发创建");
                jf.setCreatetime(new Date(0));
                jf.insert();
            }
            if (jf.getTotal().intValue() < jifen) {
                map.put("state", 0);
            } else {
                map.put("state", 1);
            }

            String[] ywdatastrgid = ywdatastr[1].split(",");//gid*1,gid*2
            List<Long> gids = new ArrayList<Long>();
            Map<String, Integer> gmap = new HashMap<String, Integer>();
            for (int i = 0; i < ywdatastrgid.length; i++) {
                String[] gidnum = ywdatastrgid[0].split("@");
                gids.add(Long.valueOf(gidnum[0]));
                gmap.put(gidnum[0], Integer.valueOf(gidnum[1]));
            }

            List<Goods> goods = goodsService.selectList(new EntityWrapper<Goods>().setSqlSelect("id,name,pic,saleprice,price,number_sale numberSale").in("id", gids));
            for (Goods item : goods) {
                item.setDhshu(gmap.get(item.getId().toString()));
            }
            map.put("list", goods);
            map.put("jifen", jifen);

        } else if (type.equals("yuyuedh")) {// 预约订单核销
            String[] ywdatastr = ywdata.split("#");
            BigDecimal pay = new BigDecimal(ywdatastr[0]);
            User guser = redisService.getUserByGuid(guid);
            hexiao.setJiazhi(pay);
            hexiao.setHxuid(guser.getId());
            hexiao.insert();

            String oid = ywdatastr[1];//gid*1,gid*2

            Order order = orderService.selectOne(new EntityWrapper<Order>()
                    .setSqlSelect("id,address,linkman,phone,realpay,status,yytime,goods_name goodsName,yytime").eq("id", oid));
            Boolean canuse = false;
            if (order == null) {
                map.put("msg", "该预约订单不存在");
            } else if (order.getStatus() <= 1) {
                map.put("msg", "该预约订单未支付");
            } else if (order.getStatus() >= 4) {
                map.put("msg", "该预约订单已核销");
            } else {
                canuse = true;
            }
            map.put("state", canuse ? 1 : 0);

            map.put("order", order);
        } else if (type.equals("jiangpindh")) {
            //奖品兑换核销
            String[] ywdatastr = ywdata.split("#");
            Long choujiangId = Long.valueOf(ywdatastr[0]);
            User guser = redisService.getUserByGuid(guid);

            hexiao.setGid(choujiangId);
            hexiao.setHxuid(guser.getId());
            hexiao.insert();

            String jpid = ywdatastr[1];//gid*1,gid*2

            ChoujiangLog choujiangLog = choujiangLogService.selectById(choujiangId);
            Choujiang jiangpin = choujiangService.selectById(jpid);

            Boolean canuse = false;
            if (jiangpin == null) {
                map.put("msg", "该奖品不存在");
            } else if (choujiangLog == null) {
                map.put("msg", "该抽奖记录无效");
            } else if (choujiangLog.getIslingqu() == 1) {
                map.put("msg", "该抽奖已领取");
            } else if (choujiangLog.getIsguoqi() == 1) {
                map.put("msg", "该抽奖已过期");
            } else {
                canuse = true;
            }

            map.put("state", canuse ? 1 : 0);
            map.put("jiangpin", jiangpin);

        } else if (type.equals("yhqdh")) {// 优惠券核销
            String[] ywdatastr = ywdata.split("#");
            Long yhqid = new Long(ywdatastr[1]);
            String couponId = ywdatastr.length >= 3 ? ywdatastr[2] : "";
            User guser = redisService.getUserByGuid(guid);
            User cuser = redisService.getUser();

            Wrapper<Coupon> wrapper = new EntityWrapper<Coupon>()
                    .eq("uid", guser.getId());
            if (!Strings.isNullOrEmpty(couponId)) wrapper.eq("id", couponId);
            else wrapper.eq("tplid", yhqid);

            Coupon coupon = couponService.selectOne(wrapper);

            Map<String, String> gmap = new HashMap<String, String>();
            String qtype = "代金券";
            if (coupon.getType() == 1) qtype = "代金券";
            if (coupon.getType() == 2) qtype = "满减券";
            if (coupon.getType() == 3) qtype = "折扣券";
            if (coupon.getType() == 4) qtype = "兑换券";

            gmap.put("yhqtype", qtype);
            String expire = Strings.isNullOrEmpty(coupon.getEndtime()) ? coupon.getStarttime() : coupon.getStarttime() + "-" + coupon.getEndtime();
            gmap.put("youxiaoday", coupon.getIsForever() == 1 ? "长期有效" : expire);
            gmap.put("dhname", guser.getNickName());
            gmap.put("dhtime", DateUtil.toDateString(new Date(), "YYYY-MM-dd HH:mm:ss"));
            if (coupon.getSid() != null && coupon.getSid() > 0) {
                Store store = storeService.selectById(coupon.getSid());
                gmap.put("sname", store != null ? store.getName() : "");
            }

            Boolean canuse = false;
            if (coupon == null) {
                map.put("msg", "该优惠券不存在");
            } else if (coupon.getIsUsed() == 1) {
                map.put("msg", "该优惠券已被使用");
            } else if (coupon.getIsOutdate() == 1) {
                map.put("msg", "该优惠券已过期");
            } else if (coupon.getSid() != null && coupon.getSid() > 0) {
                logger.info("--------------------------------------coupon.getSid()=" + coupon.getSid());
                logger.info("--------------------------------------cuser.getSid()=" + cuser.getSid());
                logger.info("--------------------------------------cuser.getIsMch()=" + cuser.getIsMch());
                if (cuser.getIsMch() == 1 && coupon.getSid().intValue() == cuser.getSid().intValue()) {
                    // 平台用户可以扫码
                    canuse = true;
                } else {
                    logger.info("--------------------------------------cuser.getSid()!=coupon.getSid()");
                    map.put("msg", "该优惠券不属于该商家");
                }
            } else {
                canuse = true;
            }
            if (canuse) {
                hexiao.setJiazhi(coupon.getCost());
                hexiao.setHxuid(guser.getId());
                hexiao.insert();
            }
            map.put("state", canuse ? 1 : 0);
            map.put("yhq", gmap);

        } else if (type.equals("yhqtykdh")) {// 优惠券体验卡核销
            String[] ywdatastr = ywdata.split("#");
            Long yhqid = new Long(ywdatastr[1]);
            String couponId = ywdatastr.length >= 3 ? ywdatastr[2] : "";
            User guser = redisService.getUserByGuid(guid);
            User cuser = redisService.getUser();

            Wrapper<Coupon> wrapper = new EntityWrapper<Coupon>()
                    .eq("uid", guser.getId()).eq("id", couponId);

            Coupon coupon = couponService.selectOne(wrapper);
            Map<String, String> gmap = new HashMap<String, String>();
            String qtype = "代金券";
            if (coupon != null && coupon.getType() == 10) qtype = "次卡";
            if (coupon != null && coupon.getType() == 11) qtype = "周卡";
            if (coupon != null && coupon.getType() == 12) qtype = "月卡";
            if (coupon != null && coupon.getType() == 13) qtype = "季卡";
            if (coupon != null && coupon.getType() == 14) qtype = "半年卡";
            if (coupon != null && coupon.getType() == 15) qtype = "年卡";
            if (coupon != null && coupon.getType() == 16) qtype = "畅游卡";

            gmap.put("yhqtype", qtype);

            String expire = Strings.isNullOrEmpty(coupon.getEndtime()) ? coupon.getStarttime() : coupon.getStarttime() + "-" + coupon.getEndtime();
            gmap.put("youxiaoday", coupon.getIsForever() == 1 ? "长期有效" : expire);
            gmap.put("dhname", guser.getNickName());
            gmap.put("dhtime", DateUtil.toDateString(new Date(), "YYYY-MM-dd HH:mm:ss"));

            if (coupon.getSid() != null && coupon.getSid() > 0) {
                Store store = storeService.selectById(coupon.getSid());
                gmap.put("sname", store != null ? store.getName() : "");
            }

            Boolean canuse = false;
            if (coupon == null) {
                map.put("msg", "该优惠券不存在");
            } else if (coupon.getIsUsed() == 1) {
                map.put("msg", "该优惠券已被使用");
            } else if (coupon.getType().intValue() == 10 && coupon.getCost().intValue() <= coupon.getUsemin().intValue()) {
                map.put("msg", "该次卡已被使用完毕");
            } else if (coupon.getIsOutdate() == 1) {
                map.put("msg", "该优惠券已过期");
            } else if (coupon.getSid() != null && coupon.getSid() > 0) {
                logger.info("--------------------------------------coupon.getSid()=" + coupon.getSid());
                logger.info("--------------------------------------cuser.getSid()=" + cuser.getSid());
                logger.info("--------------------------------------cuser.getIsMch()=" + cuser.getIsMch());
                if (cuser.getIsMch() == 1 && coupon.getSid().intValue() == cuser.getSid().intValue()) {
                    // 平台用户可以扫码
                    canuse = true;
                } else {
                    logger.info("--------------------------------------cuser.getSid()!=coupon.getSid()");
                    map.put("msg", "该优惠券不属于该商家");
                }
            } else {
                canuse = true;
            }
            if (canuse) {
                hexiao.setJiazhi(coupon.getCost());
                hexiao.setHxuid(guser.getId());
                hexiao.insert();
            }
            map.put("state", canuse ? 1 : 0);
            map.put("yhq", gmap);

        } else if (type.equals("zitihx")) {// 用户自提取货
            String[] ywdatastr = ywdata.split("#");
            Long yhqid = new Long(ywdatastr[1]);
            User guser = redisService.getUserByGuid(guid);
            Long sid = ObjectUtil.getSid();

            int state = 1;

            Order order = orderService.selectById(yhqid);
            logger.debug("-------------------------------hexiao sid=" + sid);
            logger.debug("-------------------------------hexiao order.sid=" + order.getSid());

            List<GoodsStore> gstores = goodsStoreMapper.selectList(new EntityWrapper<GoodsStore>()
                    .setSqlSelect("id,gid,sid").eq("gid", order.getGid()));
            TreeSet<Long> treeSet = new TreeSet<Long>();
            if (order.getSid() != null) treeSet.add(order.getSid());
            for (GoodsStore item : gstores) {
                treeSet.add(item.getSid());
            }
            logger.debug("-------------------------------hexiao treeSet.contains(sid)=" + treeSet.contains(sid));

            List<OrderGoods> goods = orderGoodsService.selectList(new EntityWrapper<OrderGoods>().eq("oid", yhqid));
            if (order == null) {
                info.setCode(1);
                info.setMsg("订单不存在");
                return info;
            } else if (order == null || order.getStatus() > 3) {
                info.setCode(1);
                info.setMsg("订单已核销");
                return info;
            } else if (!treeSet.contains(sid)) {
//            else if (order.getSid() != null && sid != null && sid.longValue() != order.getSid().longValue()) {
                info.setCode(1);
                info.setMsg("该订单不是本店所售，核销失败");
                return info;
            } else {
                hexiao.setJiazhi(order.getRealpay());
                hexiao.setHxuid(guser.getId());
                hexiao.insert();

                map.put("state", state);
                if (state == 1) map.put("goods", goods);
            }
        }

        info.setInfo(map);
        return info;
    }

    @RequestMapping("/api/coupon/hexiao")
    @ResponseBody
    public Jinfo quanHexiao(@RequestParam(value = "cno", required = false) String cno) {
        Jinfo jinfo = new Jinfo();
        Wrapper<Coupon> entity = new EntityWrapper<Coupon>().eq("cno", cno);
        Coupon coupon = couponService.selectOne(entity);

        if (coupon == null) jinfo.setCode(4);
        if (coupon.getIsUsed() == 1) {
            jinfo.setCode(1);
            jinfo.setMsg("该券已经被核销使用");
        }
        coupon.setIsUsed(1);
        coupon.setIsUnused(0);
        coupon.setModifytime(new Date());
        coupon.setModifier(ObjectUtil.getUid());
        coupon.insertOrUpdate();

        return jinfo;
    }


    @RequestMapping("/api/user/quanma")
    @ResponseBody
    public Jinfo quanma(@RequestParam("type") String type,
                        @RequestParam("ywdata") String ywdata) {
        logger.info("=============/api/user/quanma type=" + type);
        logger.info("=============/api/user/quanma ywdata=" + ywdata);
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(type) || Strings.isNullOrEmpty(ywdata)) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        Long ts = new Date().getTime();
        User user = redisService.getUser();
        // random(16)+"__"+type+"__"+guid+"__"+ywid+"__"+timestamp
        // type:yajin ywdata:押金数
        // type:jifendh ywdata:积分数#gid#gname#gpic#sellnum
        if (type.equals("jifendh")) {
            // 积分兑换
            String[] typearr = ywdata.split("#");
            if (typearr.length != 2) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("yuyuedh")) {
            // 预约兑换
            String[] typearr = ywdata.split("#");
            if (typearr.length < 2) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("zitihx")) {
            // 自提核销
            String[] typearr = ywdata.split("#");
            if (typearr.length != 2) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("shoukuan")) {
            // 收款核销
            String[] typearr = ywdata.split("#");
            if (typearr.length != 1) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("jiangpindh")) {
            // 奖品兑换，ywdata=jiagnpinlog_id#jiang_id
            String[] typearr = ywdata.split("#");
            if (typearr.length != 2) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("yhqdh")) {
            // 优惠券核销，ywdata="0#" + tplid+"#"+td.couponId
            String[] typearr = ywdata.split("#");
            if (typearr.length != 3) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        } else if (type.equals("yhqtykdh")) {
            // 优惠券体验卡核销，ywdata="0#" + tplid+"#"+td.couponId
            String[] typearr = ywdata.split("#");
            if (typearr.length < 2) {
                info.setCode(4);
                info.setMsg("参数有误");
                return info;
            }
        }

        logger.info("=======type=" + type);
        logger.info("=======ywdata=" + ywdata);
        logger.info("=======user=" + JSON.toJSONString(user));
        MerchantApp mapp = redisService.getMApp();

        // random(16)+"__"+type+"__"+guid+"__"+ywdata+"__"+timestamp
        String txt = ObjectUtil.randomStrings(16, 1).get(0) + "__" + type + "__" + user.getGuid() + "__" + ywdata + "__" + ts + "__" + user.getMpid() + "__" + (user.getSid() == null ? 0 : user.getSid());
        String rkey = txt;
        String key = ObjectUtil.getMid() + ObjectUtil.getAppid() + ObjectUtil.getMpid();
        logger.info("=============/api/user/quanma txt=" + txt);
        logger.info("=============/api/user/quanma key=" + key);

        txt = AesUtil.encrypt(txt, EncryptUtil.md5t16(key));
        logger.info("=============encrypt txt=" + txt);
        String url = redisService.get(rkey);
        logger.info("=============url=" + url);
        if (!Strings.isNullOrEmpty(url)) {
            info.setInfo(url);
            return info;
        }

        String path = Constants.WX_QR_PATH_TMPQR.replace("MCODE", mapp.getMcode()) + DateUtil.getShortToday() + "/" + ObjectUtil.getUid() + "/" + type + "/";
        HttpUtil.checkDirectory(path);
        path += type + "_" + ts + ".png";

        int width = 200; // 二维码图片的宽
        int height = 200; // 二维码图片的高
        String format = "png"; // 二维码图片的格式

        try {
            url = QRCodeUtil.generateQRCode(txt, width, height, format, path);
            info.setInfo(url);
            redisService.set(rkey, url, 599, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("======/apiuser/quanma generateQRCode error", e);
            info.setCode(5);
            info.setMsg(e.getMessage());
        }

        return info;
    }

}
